package com.project.service;

import com.spring.BeanPostProcessor;
import com.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author Administrator
 */
@Component("beanPostProcessor")
public class BeanPostProcessorImpl implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws Exception {
        if ("userService".equals(beanName)) {
            ((UserService) bean).setName("初始化Name成功");
            System.err.println("初始化Name成功");
        }

        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws Exception {
        if ("stuServiceImpl".equals(beanName)) {
            Object proxyInstance = Proxy.newProxyInstance(BeanPostProcessorImpl.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.err.println("代理逻辑执行前");
                    Object invoke = method.invoke(bean, args);
                    System.err.println("代理逻辑执行后");
                    return invoke;
                }
            });

            return proxyInstance;
        }

        return bean;
    }
}
